﻿/*
	* Project	: SharePoint Dynamic Forms
	* Version	: 1.0
	* Company	: SharePoint Frontier Software Pvt Ltd. (http://www.sharepointfrontier.com)
	* Author	: Ashok Raja .T (Blog : http://www.ashokraja.me)
	* Licence	: Published under Microsoft Public License (Ms-PL)
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
 

namespace SFS.SharePoint.DynamicForms
{
    public class SPDynamicForm
    {
        XmlNode xNodes = null;
        public string FormName { get; set; }
        public string ListName { get; set; }


        private SPDynamicForm() { }
        public SPDynamicForm(string FormId,string FormIdColumn, string FormData, string FormsList)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(GetXmlString(FormId, FormIdColumn,FormData, FormsList));
            xNodes = xDoc.SelectSingleNode("DynamicForms/Form");
            ListName = xNodes.Attributes["ListName"].Value;
            FormName = GetAtributeValue(xNodes, "DisplayName") ?? ListName;

        }

        public List<SPDynamicField> GetFormFields()
        {
            List<SPDynamicField> Fields = new List<SPDynamicField>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
          {
              using (SPSite site = new SPSite(SPContext.Current.Site.ID))
              {
                  using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                  {
                      SPList list = web.Lists[ListName];

                      foreach (XmlNode xNode in xNodes.SelectNodes("Fields/Field"))
                      {
                          SPDynamicField Field = new SPDynamicField();
                          Field.InternalName = xNode.Attributes["InternalName"].Value;
                          Field.DisplayName = GetAtributeValue(xNode, "DisplayName") ?? Field.InternalName;
                          Field.DefaultValue = GetAtributeValue(xNode, "DefaultValue");
                          Field.DisplayMode = GetAtributeValue(xNode, "DisplayMode");
                          try
                          {
                              foreach (XmlNode xItem in xNode.SelectNodes("Validations/Rule"))
                              {
                                  if (Field.ValidationRules.SingleOrDefault(hd => hd.ValidationType == xItem.Attributes["Type"].Value) == null)
                                  {
                                      try
                                      {
                                          SPDynamicFieldValidationRule Rule = new SPDynamicFieldValidationRule();
                                          Rule.ValidationType = xItem.Attributes["Type"].Value;
                                          Rule.ValidateAgainst = xItem.Attributes["Value"].Value;
                                          Rule.ValidationMessage = GetAtributeValue(xItem, "ErrorMessage");
                                          Field.ValidationRules.Add(Rule);
                                      }
                                      catch  
                                      {
                                      }
                                  }
                              }
                              SPDynamicFieldValidationRule rule = Field.ValidationRules.SingleOrDefault(hd => hd.ValidationType == "re");
                              if (rule == null)
                              {
                                  SPField fld = list.Fields.GetFieldByInternalName(Field.InternalName);

                                  Field.IsRequired = fld.Required;
                              }
                              else
                              {
                                  bool tempRequired = false;
                                  bool.TryParse(rule.ValidateAgainst, out tempRequired);
                                  Field.IsRequired = tempRequired;
                              }
                          }
                          catch (Exception)
                          {
                          }
                          Fields.Add(Field);
                      }
                  }
              }
          });
            return Fields;
        }

        private string GetXmlString(string FormId,string FormIdColumn, string DataColumn,string SourceList)
        {
            string FormData = "";
            SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               using (SPSite site = new SPSite(SPContext.Current.Site.ID))
               {
                   using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                   {
                       SPList list = web.Lists[SourceList];
                       SPListItem item = list.Items.OfType<SPListItem>().SingleOrDefault(hd => hd[FormIdColumn].ToString() == FormId);
                       FormData = item[DataColumn].ToString();
                       FormName = list.Title;
                   }
               }
           });
            return FormData;
        }

        private string GetAtributeValue(XmlNode xNode, string AttributeName)
        {
            try
            {
                return xNode.Attributes[AttributeName] == null ? null : xNode.Attributes[AttributeName].Value;
            }
            catch
            {
                return null;
            }
        }
    }
}
